package com.pine.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.InputStream;


@Slf4j
public class ImageFileUtil {

    /**
     * 日志对象
     */
    @Value("${ossAccessKeyId}")
    private String ossAccessKeyId;
    @Value("${ossAccessKeySecre}")
    private String ossAccessKeySecre;
    @Value("${ossSendPoint}")
    private String ossSendPoint;
    @Value("${ossBucketName}")
    private String ossBucketName;
    @Value("${aliImageSever}")
    private String aliImageSever;

    public String upLocadImage(InputStream fin, String path) {

        log.info("UpLoadImage :上传照片 开始  ： fin：" + fin + "; phth: " + path);
        String aliid = this.ossAccessKeyId;
        String alikey = this.ossAccessKeySecre;
        String aliossendpoit = this.ossSendPoint;
        String bucketname = this.ossBucketName;
        OSSClient client = new OSSClient(aliossendpoit, aliid, alikey);
        OSSObject object = null;
        log.info("UpLoadImage :上传照片  ： aliid：" + aliid + "; alikey: " + alikey + "; aliossendpoit : " + aliossendpoit + "; bucketname:"
                + bucketname);
        if (path.startsWith("/")) {
            return "invalid path";
        }
        @SuppressWarnings("unused")

        PutObjectResult result = client.putObject(bucketname, path, fin, new ObjectMetadata());

        try {
            object = client.getObject(bucketname, path);
        } catch (Exception r) {
            log.error("UpLoadImage: 上传照片异常 ", r);
        }

        // 如果不设置content-length, 默认为chunked编码。
        if (object != null) {
            return "file exist";
        }

        return "success";
    }


    public String GetRealImagePath(String Path) {

        if (Path == null || "".equals(Path) || Path.startsWith("images")) {
            return Path;
        }
        return aliImageSever + "/" + Path;
    }


}
